package com.lengxf.pay.wx.service;

import com.lengxf.pay.common.bean.PayOrder;
import com.lengxf.pay.wx.config.WX_PayConfig;
import com.lengxf.pay.wx.transfer.OsTransfer;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.h5.model.*;

public record WxH5PayService(Config config, WX_PayConfig wxPayConfig) {

    public String qrPay(PayOrder payOrder) {
        H5Service h5Service = new H5Service.Builder().config(config).build();
        PrepayResponse prepay = h5Service.prepay(buildRequest(payOrder));
        return prepay.getH5Url();
    }

    private PrepayRequest buildRequest(PayOrder payOrder) {
        PrepayRequest request = new PrepayRequest();
        request.setAppid(wxPayConfig.getAppid());
        request.setMchid(wxPayConfig.getMerchantId());
        request.setDescription(payOrder.getProductDesc());
        request.setOutTradeNo(payOrder.getOrderNo());
        request.setNotifyUrl(wxPayConfig.notifyUrl());
        //构建金额数据
        Amount amount = new Amount();
        amount.setTotal(payOrder.getPrice().intValue());
        request.setAmount(amount);
        //构建场景数据
        SceneInfo sceneInfo = new SceneInfo();
        sceneInfo.setPayerClientIp(payOrder.getOrderCreateIp());
        H5Info h5Info = new H5Info();
        h5Info.setType(OsTransfer.transfer(payOrder.getOsType()));
        sceneInfo.setH5Info(h5Info);
        request.setSceneInfo(sceneInfo);
        return request;
    }


}
